package com.yunze.system.card;

import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.Channel;
import com.yunze.common.mapper.mysql.warehouse.Administration.YzCkglInventorydetailsMapper;
import com.yunze.common.mapper.mysql.YzExecutionTaskMapper;
import com.yunze.common.utils.yunze.Different;
import com.yunze.common.utils.yunze.ExcelConfig;
import com.yunze.common.utils.yunze.WriteCSV;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Component
public class ImportDetails {

    @Resource
    private YzExecutionTaskMapper yzExecutionTaskMapper;
    @Resource
    private WriteCSV writeCSV;
    @Resource
    private YzCkglInventorydetailsMapper yzCkglInventorydetailsMapper;

    /**导入*/

    @RabbitHandler
    @RabbitListener(queues = "admin_uploadDetails_queue")
    public void Import(String msg, Channel channel) throws IOException  {
        try {
            if(StringUtils.isEmpty(msg)){
                return;
            }
            Map<String,Object> map = JSON.parseObject(msg);
            String filePath = map.get("filePath").toString();//项目根目录
            String ReadName = map.get("ReadName").toString();//上传新文件名
            String newName = map.get("newName").toString();//输出文件名
            Map<String,Object> User =  ( Map<String,Object>)map.get("User");//登录用户信息
            Map<String,Object> Pmap =  ( Map<String,Object>)map.get("Pmap");//
            Map<String,Object> parammap =  ( Map<String,Object>)map.get("parammap");//


            ImportCar(filePath,ReadName,User,newName,Pmap,parammap);//执行导入

        }catch (Exception e){
            log.error(">>错误 - 批量导入卡 <<", e.getMessage().toString());
        }
    }

    /**
     * 导入执行
     * */


    private void ImportCar(String filePath, String ReadName, Map<String, Object> User, String newName, Map<String, Object> Pmap,Map<String, Object> parammap) {

        String path = filePath + ReadName;
        ExcelConfig excelConfig = new ExcelConfig();
        String columns[] = { "CaseNumber","PlateNumber", "productCode","arraylNumber","batchNumber","Pkg_Id","MAC",
                "DeviceCode","SerialNumber","SN","Original_SN","iccid","IMSI","IMEI","CMEI"};
        String maxVid = yzCkglInventorydetailsMapper.selMaxVid();
        maxVid = maxVid != null?maxVid:"16900000000";
        Long  maxVidInt = Long.parseLong(maxVid);

        List<Map<String, String>> list = excelConfig.getExcelListMap(path,columns,maxVidInt);
        Map<String, String> Dept = (Map<String, String>)User.get("dept");
        String  create_by = " [ "+Dept.get("deptName")+" ] - "+" [ "+User.get("userName")+" ] ";

        String Outcolumns[] = {"IMEI","操作描述","执行时间","执行结果","执行人"};
        String keys[] = {"IMEI","description","time","result","agentName"};

        if(list!=null && list.size()>0){

            String SaveUrl = "/getcsv/"+newName+".csv";
            String task_name ="仓库管理上传 [导入] ";
            Map<String, Object> task_map = new HashMap<String, Object>();
            task_map.put("auth",create_by);
            task_map.put("task_name",task_name);
            task_map.put("url",SaveUrl);
            task_map.put("agent_id", Dept.get("deptId"));
            task_map.put("type","13");
            yzExecutionTaskMapper.add(task_map);//添加执行 任务表

            //判断是否含有必须上传参数
            List<Map<String, String>> qualifiedArr = new ArrayList<>();
            List<Map<String, String>> ontQualifiedArr = new ArrayList<>();
            for (int i = 0; i < list.size() ; i++) {
                Object IMEI = list.get(i).get("IMEI");
                Object CaseNumber = list.get(i).get("CaseNumber");
                if(IMEI != null && IMEI.toString().length()>0 && CaseNumber !=null && CaseNumber.toString().length()>0){
                    qualifiedArr.add(list.get(i));
                }else {
                    ontQualifiedArr.add(list.get(i));
                }
            }
            //不合格的上传数据输出 提示 上传文件必填参数缺失
            if(ontQualifiedArr.size()>0){
                writeCSV.OutCSV(ontQualifiedArr,newName,"上传文件必填参数缺失！",create_by,"导入失败",Outcolumns,keys,"IMEI");
            }
            //更新 符合上条件的 数组
            list = qualifiedArr;


            //筛选出 IMEI 的 卡号 重复项
            HashMap<String, Object> map = new HashMap<>();
            map.put("Import_arrs",list);
            map.put("type","1");

            List<String>  iccidarr = yzCkglInventorydetailsMapper.iMEIStock(map);


            //1.判断上传数据与数据库现有数据做对比 大于 0 证明有 以存在数据
            if(iccidarr.size()>0){
                //上传数据>数据库查询 赛选出
                List<String> list1 = new ArrayList<>();
                for (int i = 0; i <list.size() ; i++) {
                    list1.add((String) list.get(i).get("IMEI"));
                }
                //找出与数据库已存在 相同 ICCID 去除 重复 iccid
                List<Map<String, String>> Out_list_Different = Different.getIdentical(list1,iccidarr,"IMEI");
                if(Out_list_Different.size()>0){
                    writeCSV.OutCSV(Out_list_Different,newName,"IMEI重复导入失败！",create_by,"导入失败",Outcolumns,keys,"IMEI");
                }
                list = Different.delIdentical(list,iccidarr,"IMEI");//删除相同的数据 进行批量上传
            }
            map.put("Import_arrs",list);//更新 list
            map.put("CSDS_ID",parammap.get("CSDS_ID"));
            map.put("Cy_ID",parammap.get("Cy_ID"));
            map.put("create_by",create_by);
            try {
                if(list.size()>0){
                    //int  sInt =  yzCkglInventorydetailsMapper.importStock(map);//导入
                    int  sInt = 0;
                    //导入批量处理 2k 条
                    List<Map<String, String>> listnew = new ArrayList<>();
                    Map<Integer, List<Map<String, String>>> lMap=new HashMap<>();
                    int MaxAdd = 2000;
                    for(int i=0;i<list.size();i++) {
                        if(i==0 ||i%MaxAdd==0) {
                            listnew=new ArrayList<Map<String, String>>();
                            listnew.add(list.get(i));
                            lMap.put(i+1, listnew);
                        }else {
                            //listnew=new ArrayList<String>();
                            listnew.add(list.get(i));
                        }
                    }
                    for(Integer key : lMap.keySet()){
                        map.put("Import_arrs",lMap.get(key));//更新 list
                        map.put("CSDS_ID",parammap.get("CSDS_ID"));
                        map.put("Cy_ID",parammap.get("Cy_ID"));
                        map.put("create_by",create_by);
                        sInt +=  yzCkglInventorydetailsMapper.importStock(map);//导入
                    }

                    if(sInt>0){
                        writeCSV.OutCSV(list,newName,"成功导入卡列表数据 ["+sInt+"] 条",create_by,"导入成功",Outcolumns,keys,"IMEI");
                        yzExecutionTaskMapper.set_end_time(task_map);//任务结束
                    }
                }else{
                    yzExecutionTaskMapper.set_end_time(task_map);//任务结束
                    log.error(">> admin-消费者- 上传数据已全部在数据库，无需上传卡信息！ :{}<<");
                }
            }catch (DuplicateKeyException e){
                System.out.println("===="+e.getCause().toString());
                writeCSV.OutCSV(list,newName,e.getCause().toString(),create_by,"导入失败",Outcolumns,keys,"IMEI");
                yzExecutionTaskMapper.set_end_time(task_map);//任务结束
                log.error(">> admin-消费者- 上传excel异常 [插入数据 DuplicateKeyException ] :{}<<", e.getMessage().toString());
            }catch (Exception e){
                writeCSV.OutCSV(list,newName,e.getCause().toString(),create_by,"导入失败",Outcolumns,keys,"IMEI");
                yzExecutionTaskMapper.set_end_time(task_map);//任务结束
                log.error(">>admin-消费者- 批量导卡消费者:{}<<", e.getMessage().toString());
            }
        }else{
            log.error( "admin-消费者 上传表格无数据！无需执行导入");
        }
    }



}




